<template>
  <div class="exam-list">
    <div class="list-header">
      <h2>考试列表</h2>
      <div class="filters" style="width: 20%;">
        <el-select v-model="filters.subjectId" placeholder="选择科目" clearable>
          <el-option v-for="subject in subjects" :key="subject.id" :label="subject.name" :value="subject.id" />
        </el-select>

        <el-select v-model="filters.status" placeholder="考试状态" clearable>
          <el-option v-for="item in examStatus" :key="item.code" :label="item.description" :value="item.description" />
        </el-select>
      </div>
    </div>

    <el-table v-loading="loading" :data="examList" border style="width: 100%">
      <el-table-column prop="examinationType" label="考试类型" width="120" />
      <el-table-column prop="name" label="考试名称" width="180" />
      <el-table-column prop="subjectName" label="科目" width="120" />
      <el-table-column label="考试时间" width="400">
        <template #default="{ row }">
          {{ row.startTime }} ~ {{ row.endTime }}
        </template>
      </el-table-column>
      <el-table-column prop="totalScore" label="总分" width="100" />
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.examinationStatus)">
            {{ row.examinationStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <!-- TODO 封装学生状态 -->
          <el-button v-if="row.examinationStatus !== '已批阅' && row.studentStatus === 'permitted'" type="primary"
            size="small" @click="handleStartExam(row)">
            进入考试
          </el-button>
          <el-button v-if="row.examinationStatus === '已批阅'" type="info"
            size="small" @click="handleViewScore(row)">
            查看成绩
          </el-button>
          <el-button v-if="row.examinationStatus !== '已批阅' && row.studentStatus !== 'permitted'" type="info"
            size="small" >
            不可进入考试
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getExamList, getSubjectsAndStatus } from '@/api/th/exam'

const router = useRouter()
const loading = ref(false)
const examList = ref([])

// 模拟科目数据，实际应该从API获取
const subjects = ref([
  { id: 1, name: '数学' },
  { id: 2, name: '语文' },
  { id: 3, name: '英语' }
])

const filters = reactive({
  subjectId: null,
  status: null
})

// 考试状态枚举
const examStatus = ref( [
  { code: 1, description: '正在考试'}
])

// 当筛选条件变化时重新加载列表
watch(filters, () => {
  fetchExamList()
})

const fetchSubjectListAndExamStatus = async () => {
  loading.value = true
  try {
    const { data } = await getSubjectsAndStatus()
    subjects.value = data.subjects || []
    examStatus.value  = data.status || []
  } catch (error) {
    ElMessage.error('获取学科列表失败，请刷新页面重试')
    console.error('获取学科列表失败', error)
  } finally {
    loading.value = false
  }
}


const fetchExamList = async () => {
  loading.value = true
  try {
    const { data } = await getExamList({
      subjectId: filters.subjectId,
      status: filters.status
    })
    examList.value = data.list
  } catch (error) {
    ElMessage.error('获取考试列表失败，请刷新页面重试')
    console.error('Failed to fetch exam list:', error)
  } finally {
    loading.value = false
  }
}

// 状态样式
const getStatusType = (status) => {
  const types = {
    '正常考试': 'success',
    '暂停登录': 'warning',
    '待分配': 'info',
    '批阅中': 'primary',
    '已批阅': ''
  }
  return types[status] || 'info'
}


const handleStartExam = (exam) => {
  if (exam.studentStatus === 'inProgress') {
    router.push(`/exam/${exam.id}/take`)
  } else {
    router.push(`/exam/${exam.id}`)
  }
}

const handleViewScore = (exam) => {
  router.push(`/score/${exam.id}`)
}

onMounted(() => {
  fetchSubjectListAndExamStatus()
  fetchExamList()
})
</script>

<style scoped>
.exam-list .list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.exam-list .list-header h2 {
  margin: 0;
}

.exam-list .list-header .filters {
  display: flex;
  gap: 16px;
}
</style>